package com.neu.daoimpl;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.neu.dao.GoodsDao;
import com.neu.entity.Goods;
import com.neu.util.JDBCUtil;

public class GoodsDaoImpl implements GoodsDao {
	/**
	 * 查看全部的商品信息
	 */
	@Override
	public List<Goods> selects() throws SQLException {
		Connection conn=null;
		try {
			 conn = JDBCUtil.getConn();
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String sql = "select * from goods ";
		PreparedStatement ps = conn.prepareStatement(sql);
		ResultSet rs = ps.executeQuery();
		List<Goods> list = new ArrayList<>();
		while(rs.next()) {
			list.add(new Goods(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getInt(4)));
		}
		return list;
	}
	/**
	 * 查看单一的商品信息
	 */
	@Override
	public Goods select(int id) throws SQLException {
		Connection conn = null;
		try {
			conn = JDBCUtil.getConn();
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String sql = "select* from Goods where id=?";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setInt(1, id);
		Goods gd = null;
		ResultSet rs = ps.executeQuery();
		if(rs.next()) {
			gd = new Goods(rs.getInt(1), rs.getString(2), rs.getInt(3), rs.getInt(4));
		}
		return gd;
	}
	/**
	 *  修改商品的信息
	 */
	@Override
	public boolean update(Goods gd) throws SQLException {
		Connection conn = null;
		boolean falg = false;
		try {
			conn = JDBCUtil.getConn();
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String sql = "update goods set name=?,price=?,count=? where id=?";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, gd.getName());
		ps.setInt(2, gd.getPrice());
		ps.setInt(3, gd.getCount());
		ps.setInt(4, gd.getId());
		int a = ps.executeUpdate();
		if(a>0) {
			System.out.println("修改成功");
		}
		return falg;
	}
	/**
	 *  增加商品的信息：
	 */
	@Override
	public boolean insert(Goods gd) throws SQLException {
		Connection conn=null;
		boolean flag = false;
		try {
			conn = JDBCUtil.getConn();
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String  sql = "insert into goods value (null,?,?,?)";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, gd.getName());
		ps.setInt(2, gd.getPrice());
		ps.setInt(3, gd.getCount());
		int a = ps.executeUpdate();
		if(a>0) {
			System.out.println("增加成功");
		}
		return flag;
	}

}
